﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Marmat.Foundation;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 关联控件。
    /// </summary>
    public class AdvDataDictionaryControl : Marmat.Forms.ComboBox
    {
        private string key;

        /// <summary>
        /// 获取或设置数据字典的key值。
        /// </summary>
        [DefaultValue(null)]
        public string Key
        {
            get => key;
            set
            {
                key = value;
                if (!this.DesignMode)
                {
                    if (!string.IsNullOrEmpty(this.Key))
                        this.LoadDataDictionary();
                    else
                        this.DataSource = null;
                }
            }
        }

        /// <summary>
        /// 加载数据字典。
        /// </summary>
        public void LoadDataDictionary()
        {
            IDataDictionary dictionary = Marmat.FrameWork.SystemCommand.GetService<IDataDictionary>();
            if (dictionary is not null)
            {
                var data = dictionary.GetDataDictionary(this.Key);
                foreach (var item in data)
                {
                    if (string.IsNullOrEmpty(item.Text))
                        item.Text = item.Value;
                }
                this.DataSource = data;
                this.ValueMember = nameof(IDataDictionaryItem.Value);
                this.DisplayMember = nameof(IDataDictionaryItem.Text);
            }
        }
    }
}
